package com.kongjs.application.advice;

import com.kongjs.application.model.entity.Options;
import com.kongjs.application.model.entity.Terms;
import com.kongjs.application.service.IOptionsService;
import com.kongjs.application.service.ITermsService;
import com.kongjs.common.rest.advice.GlobalControllerAdvice;
import com.kongjs.common.rest.annotation.Page;
import com.kongjs.common.rest.model.vo.R;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@ControllerAdvice(annotations = Page.class, basePackages = "com.kongjs.application.controller")
public class PageControllerAdvice extends GlobalControllerAdvice {
    @Resource
    private ITermsService termsService;
    @Resource
    private IOptionsService optionsService;

    @ModelAttribute("navs")
    public List<Terms> navs() {
        return termsService.lambdaQuery()
                .eq(Terms::getTermGroup, 0).list();
    }

    @ModelAttribute("options")
    public Map<String, String> options() {
        return optionsService.lambdaQuery()
                .eq(Options::getAutoload, "1")
                .list()
                .stream()
                .collect(Collectors.toMap(Options::getOptionName, Options::getOptionValue));
    }

    @ExceptionHandler(BadSqlGrammarException.class)
    public ModelAndView handlerBadSqlGrammarException(BadSqlGrammarException ex, WebRequest request) {
        HttpHeaders headers = new HttpHeaders();
        headers.setCacheControl(CacheControl.noCache());
        R error = error(ex, HttpStatus.INTERNAL_SERVER_ERROR, ex.getClass().getName(), null, "数据库操作异常");
        log.error("数据库操作异常", ex);
        ModelAndView view = handleExceptionInternal(ex, error, headers, HttpStatus.INTERNAL_SERVER_ERROR, request);
        view.setViewName("/error/500");
        return view;
    }
}
